package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.dto.RoutineSlotRequest;
import com.ruoyi.livedemo.entity.RoutineSlot;
import com.ruoyi.livedemo.mapper.RoutineSlotMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class RoutineService {

    private final RoutineSlotMapper routineSlotMapper;

    public PagedResult<RoutineSlot> list(Long userId, int page, int size) {
        int pageSize = size <= 0 ? 10 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<RoutineSlot> items = routineSlotMapper.findPage(userId, offset, pageSize);
        long total = routineSlotMapper.countByUser(userId);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public RoutineSlot create(Long userId, RoutineSlotRequest request) {
        RoutineSlot slot = new RoutineSlot();
        slot.setUserId(userId);
        slot.setLabel(request.getLabel());
        slot.setTimeRange(request.getTimeRange());
        slot.setDescription(request.getDescription());
        slot.setEmoji(request.getEmoji());
        slot.setBackgroundPath(request.getBackgroundPath());
        slot.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0);
        routineSlotMapper.insert(slot);
        return slot;
    }

    @Transactional
    public RoutineSlot update(Long userId, Long id, RoutineSlotRequest request) {
        RoutineSlot slot = new RoutineSlot();
        slot.setId(id);
        slot.setUserId(userId);
        slot.setLabel(request.getLabel());
        slot.setTimeRange(request.getTimeRange());
        slot.setDescription(request.getDescription());
        slot.setEmoji(request.getEmoji());
        slot.setBackgroundPath(request.getBackgroundPath());
        slot.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0);
        int rows = routineSlotMapper.update(slot);
        if (rows == 0) {
            throw new IllegalArgumentException("未找到对应的作息安排");
        }
        return slot;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        routineSlotMapper.delete(id, userId);
    }
}

